#include <iostream>  
#include <fstream>  
#include <cstdio>  
#include <cstdlib>  
#include <ctime>  
#include <sys/stat.h>  
#include <fcntl.h>  
#include <unistd.h>  
  
// 获取文件大小  
long getFileSize(const char* filename) {  
    struct stat stat_buf;  
    int rc = fstat(fileno(fopen(filename, "rb")), &stat_buf);  
    return rc == 0 ? stat_buf.st_size : -1;  
}  
  
// 高精度计时器  
struct Timer {  
    timespec start, end;  
  
    void startTimer() {  
        clock_gettime(CLOCK_REALTIME, &start);  
    }  
  
    void stopTimer() {  
        clock_gettime(CLOCK_REALTIME, &end);  
    }  
  
    double getElapsedTime() const {  
        return (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1e9;  
    }  
};  
  
int main() {  
    const char* filename = "K:/data/d2sci_write_multithread.txt"; // 替换为你的文件名  
  
    // 获取文件大小  
    long fileSize = getFileSize(filename);  
    if (fileSize == -1) {  
        std::cerr << "Error: Could not get file size." << std::endl;  
        return EXIT_FAILURE;  
    }  
    printf("file size %ld bytes\n",fileSize);
  
    // 分配缓冲区  
    char* buffer = (char*)malloc(fileSize);  
    if (!buffer) {  
        std::cerr << "Error: Could not allocate memory." << std::endl;  
        return EXIT_FAILURE;  
    }  
  
    // 打开文件  
    // int fd = open(filename, O_RDONLY);  
    // if (fd == -1) {  
    //     std::cerr << "Error: Could not open file." << std::endl;  
    //     free(buffer);  
    //     return EXIT_FAILURE;  
    // }
    FILE * fp = fopen(filename, "rb");
  
    // 计时开始  
    Timer timer;  
    timer.startTimer();  
  
    // 读取文件内容到缓冲区  
    ssize_t bytesRead = fread(buffer, 1 , fileSize/1, fp); 
    printf("bytesRead = %lld\n",bytesRead); 

    // if (bytesRead != fileSize) {  
    //     std::cerr << "Error: Could not read entire file." << std::endl;  
    //     close(fd);  
    //     free(buffer);  
    //     return EXIT_FAILURE;  
    // }  
  
    // 计时结束  
    timer.stopTimer();  
  
    // 关闭文件  
    fclose(fp);  
  
    // 输出读取时间和文件内容（可选）  
    std::cout << "File read in " << timer.getElapsedTime()*1e3 << " ms (us precision)  " << 1.0*fileSize/1024/1024/1024 / timer.getElapsedTime() << "GB/s" << std::endl;  
    // std::cout.write(buffer, fileSize); // 如果需要输出文件内容，可以取消注释这一行  
  
    // 释放缓冲区  
    free(buffer);  
  
    return EXIT_SUCCESS;  
}